<?php
error_reporting(E_ERROR);
ini_set('display_errors', '1');
require_once 'constants.php';

class Mysql{
	public function __construct()
	{
		mysql_connect(DB_SERVER,DB_USER,DB_PASS);
		mysql_select_db(DB_NAME);
	}
	
	public function __destruct() {
    	mysql_close();
    }
	/* return the user id if the login is correct */
	public function verify_login($login,$pass){
		$sql="SELECT * FROM users WHERE nom='$login' AND pass='$pass' LIMIT 1";
		$requete = mysql_query($sql) or die ($sql."<br />".mysql_error()) ;
			if($result = mysql_fetch_array($requete))
		  		return $result['id_user'];
			else
				return false;
	}
	public function get_correct_response($question_id){
		$sql = mysql_query("SELECT * FROM reponses WHERE id_question=".$question_id." AND est_juste='1' LIMIT 1") or die ($sql."<br />".mysql_error()) ;
		$row = mysql_fetch_assoc($sql);
		return $row['id_reponse'];
	}
	public function incrementer_score($id_user){
		$sql = mysql_query("UPDATE `users` SET `score` = `score`+1 WHERE `users`.`id_user` =".$id_user." LIMIT 1");
	}
	public function get_score($id_user){
		$sql = mysql_query("SELECT * FROM `users` WHERE id_user =".$id_user." LIMIT 1");
		$row = mysql_fetch_assoc($sql);
		return $row['score'];
	}	
	public function incrementcount($id_user){
		/*TO DO : we increment question's pointer by one , and if we have like this array 1,2,3,4,6,7, when we want the 5 question we have nothing
		tht's men the we must reload the page twice to get the 6 qustion , 
		what will happen if we have this 1,2,4,70,50,150,75 ?
		problem !!
		*/
		$sql = mysql_query("UPDATE `users` SET `question_pointer` = `question_pointer`+1 WHERE `users`.`id_user` =".$id_user." LIMIT 1");
	}
	public function getCountPointer($id_user){
		$sql = mysql_query("SELECT * FROM `users` WHERE id_user =".$id_user." LIMIT 1");
		$row = mysql_fetch_assoc($sql);
		return $row['question_pointer'];
	}
	public function setResponse($user_id,$question_id,$reponse_id){
		$req = <<<ENDOFQUERY
		INSERT INTO `qcm`.`user_question_reponse` (
		`id_uer` ,
		`id_question` ,
		`id_reponse`
		)
		VALUES (
		'$user_id', '$question_id', '$reponse_id'
		)
ENDOFQUERY;
		$sql = mysql_query($req);
	}
	public function getState($competition_id,$user_id){
		$sql = mysql_query("SELECT etat,description,logo FROM competition a,users b WHERE a.id_competition =".$competition_id." AND id_user=".$user_id." LIMIT 1");	
		return mysql_fetch_assoc($sql);
	}
	public function getUsersScoreList($competition_id){
		$data = array();
		$sql = mysql_query("SELECT nom,score FROM `users`");
		while ($row = mysql_fetch_assoc($sql)) {
			$data[$row['nom']] = $row['score'];
		}
		return $data;
	}
}
?>